/*
 * inotify-sync - a simple file synchronizer and file system watcher
 * Copyright (C) 2010-2011, inotify-sync developers and inotify-sync contributors
 * Copyright (C) 2010-2011, Cohesion Network Security Studio
 *
 * inotify-sync is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * inotify-sync is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with inotify-sync; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * FILE:		ProfileFileParser.cpp
 * USAGE:		---
 * DESCRIPTION:		---
 * OPTIONS:		---
 * REQUIREMENTS:	---
 * BUGS:		---
 * NOTES:		---
 * AUTHOR:		LI Yiwei (mail:leeyiw@gmail.com)
 * COMPANY:		---
 * VERSION:		1.0
 * CREATED:		Sat Nov 19 17:09:10 CST 2011
 * REVISION:		---
 */

#include "ProfileFileParser.h"

ProfileFileParser::ProfileFileParser(std::string profile_dir)
:
profile_dir(profile_dir)
{}

ProfileFileParser::~ProfileFileParser()
{}

std::vector<Profile>
ProfileFileParser::get_profiles()
{
	DIR *dir = opendir(profile_dir.c_str());
	if(dir == NULL)
	{
		perror(profile_dir.c_str());
		exit(errno);
	}
	std::vector<Profile> profile_vec;
	struct dirent *ptr;
	while((ptr = readdir(dir)) != NULL)
	{
		if(ptr->d_name[0] == '.')
		{
			continue;
		}
		FILE *fp;
		std::string profile_path = profile_dir + "/" + ptr->d_name;
		if((fp=fopen(profile_path.c_str(),"r")) == NULL)
		{
			perror(profile_path.c_str());
			exit(errno);
		}

		char buf[1000];
		Profile profile = Profile();
		while(NULL!=fgets(buf,sizeof(buf),fp))
		{
			if(is_note(buf))
				continue;
			std::string popt_str=string(buf);
			std::string::size_type equal_pos=popt_str.find('=');
			std::string::size_type end_pos=popt_str.find('\n');
			if(equal_pos==std::string::npos)
				continue;
			struct popt o;
			o.name=popt_str.substr(0,equal_pos);
			std::string::size_type val_len=end_pos-equal_pos-1;
			o.value=popt_str.substr(equal_pos+1,val_len);
			profile.add_popt(o);

			memset(buf, '\0', sizeof(buf));
		}
		fclose(fp);
		profile_vec.push_back(profile);
	}
	closedir(dir);
	return profile_vec;
}

bool
ProfileFileParser::is_note(char *buf)
{
	if(buf[0]=='#')
		return true;
	return false;
}
